<script setup name="BizUserTixianIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import { parseTime, addDateRange } from "@/utils/aidex";
import { getDicts } from "@/api/system/dict/data";
import { selectDictLabel } from "@/utils/aidex";
import {
  listBizUserTixian,
  delBizUserTixian,
  exportBizUserTixian,
  torePay,
  rollbackAccount,
  getTransferBatchesDetails,
  updateBizUserTixian
} from "@/api/biz/bizUserTixian";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();

const data = ref({
  loading: false,
  dialogFormVisible: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  // 搜索
  search: {
    name: "",
    phone: "",
    searchDate: [],
    status: ""
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  tixianStatusList: [],
  form: { remark: "" },
  id: ""
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  getDicts("tixian_status").then((res) => {
    data.value.tixianStatusList = res.data;
  });
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});
function statusFormat(row) {
  if (row.status) {
    console.log("xx", row.status);
    return selectDictLabel(data.value.tixianStatusList, row.status);
  } else {
    return "";
  }
}
// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
function clear() {
  data.value.search.name = "";
  data.value.search.phone = "";
  data.value.search.status = "";
  data.value.search.searchDate = [];
  getDataList();
}

// 查询
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.name && (params.name = data.value.search.name);
  data.value.search.phone && (params.phone = data.value.search.phone);
  data.value.search.status && (params.status = data.value.search.status);
  listBizUserTixian(addDateRange(params, data.value.search.searchDate)).then(
    (res) => {
      data.value.loading = false;
      data.value.dataList = res.data.list;
      pagination.value.total = res.data.total;
    }
  );
}

// 编辑
function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.visible = true;
  }
}
function handleUpdate() {
  updateBizUserTixian({
    id: data.value.id,
    status: "2",
    remark: data.value.form.remark
  }).then((res) => {
    if (res.code == 200) {
      ElMessage.success({
        message: "操作成功！",
        center: true
      });
      getDataList();
    }
  });
}
function getDetails(row) {
  data.value.loading = true;
  if (row.status == "-1") {
    ElMessage.warn({
      message: "失败状态的订单不能对账",
      center: true
    });
    data.value.loading = false;
    return;
  }
  if (row.wxPayNo) {
    getTransferBatchesDetails(row).then((res) => {
      console.log(res.data);
      ElMessage.success({
        message: res.msg,
        center: true
      });
      getDataList();
    });
  } else {
    ElMessage.warn({
      message: "未付款订单不能对账",
      center: true
    });
    return;
  }
}
function rePay(row) {
  ElMessageBox.confirm("确认给「" + row.phone + "」重新付款吗？", "确认信息")
    .then(() => {
      torePay(row).then((res) => {
        if (res.code == 200) {
          ElMessage.success({
            message: "操作成功",
            center: true
          });
          getDataList();
        }
      });
    })
    .catch(() => {});
}

function rollbackUserAccount(row) {
  ElMessageBox.confirm("确认「" + row.phone + "」退回余额吗？", "确认信息")
    .then(() => {
      rollbackAccount(row).then((res) => {
        if (res.code == 200) {
          ElMessage.success({
            message: "操作成功",
            center: true
          });
          getDataList();
        }
      });
    })
    .catch(() => {});
}
// 添加
function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
// 批量删除 单独删除
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="4">
              <el-form-item label="用户姓名">
                <el-input
                  v-model="data.search.nikeName"
                  placeholder="请输入用户姓名"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <el-form-item label="联系电话">
                <el-input
                  v-model="data.search.phone"
                  placeholder="请输入联系电话"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="提现时间">
                <el-date-picker
                  v-model="data.search.searchDate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="状态">
                <el-select v-model="data.search.status" clearable>
                  <el-option
                    v-for="(item, index) in data.tixianStatusList"
                    :key="index"
                    :value="item.dictValue"
                    :label="item.dictLabel"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="currentChange()">
                <template #icon>
                  <el-icon>
                    <svg-icon name="ep:search" />
                  </el-icon>
                </template>
                查询
              </el-button>
              <el-button @click="clear()">
                <template #icon>
                  <el-icon>
                    <svg-icon name="ant-design:reload-outlined" />
                  </el-icon>
                </template>
                重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>

      <div style="height: calc(100vh - 330px); overflow-y: auto">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          @sort-change="sortChange"
          @selection-change="data.batch.selectionDataList = $event"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
          />
          <el-table-column
            prop="id"
            label="流水号"
            show-overflow-tooltip
            align="center"
            width="175"
          >
            <template v-slot="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column
            prop="nikeName"
            label="用户姓名"
            show-overflow-tooltip
            align="center"
            width="120"
          >
            <template v-slot="scope">
              {{ scope.row.nikeName }}
            </template>
          </el-table-column>
          <el-table-column
            prop="phone"
            label="联系电话"
            show-overflow-tooltip
            align="center"
            width="120"
          >
            <template v-slot="scope">
              {{ scope.row.phone }}
            </template>
          </el-table-column>

          <el-table-column
            prop="money"
            label="提现金额"
            show-overflow-tooltip
            align="right"
            width="100"
          >
            <template v-slot="scope" style="font-weight: bold">
              ¥&nbsp;{{ scope.row.money }}
            </template>
          </el-table-column>

          <el-table-column
            prop="status"
            label="状态"
            show-overflow-tooltip
            align="center"
            width="90"
          >
            <template v-slot="scope">
              <!-- （0待审核 1 已打款 2 已到账 -1 驳回 99 打款失败） -->
              <el-tag :class="'ml-' + scope.row.status" type="success"
                >{{ statusFormat(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="createTime"
            label="申请时间"
            show-overflow-tooltip
            width="175"
          >
            <template v-slot="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>
          <el-table-column
            prop="payTime"
            label="支付时间"
            show-overflow-tooltip
            width="175"
          >
            <template v-slot="scope">
              {{ scope.row.payTime }}
            </template>
          </el-table-column>

          <el-table-column
            prop="wxPayNo"
            label="批次号"
            show-overflow-tooltip
            width="180"
            align="center"
          >
            <template v-slot="scope">
              {{ scope.row.wxPayNo }}
            </template>
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注"
            show-overflow-tooltip
            width="100"
          >
            <template v-slot="scope">
              {{ scope.row.remark }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="rePay(scope.row)"
                  v-if="scope.row.status == '99'"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:pay-circle-outlined" />
                    </el-icon>
                  </template>
                  重新付款</el-button
                >
                <el-button
                  type="warning"
                  size="small"
                  text
                  @click="rollbackUserAccount(scope.row)"
                  v-if="scope.row.status == '99'"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ant-design:pay-circle-outlined" />
                    </el-icon>
                  </template>
                  退回余额</el-button
                >

                <el-button
                  type="primary"
                  text
                  size="small"
                  @click="getDetails(scope.row)"
                  v-if="scope.row.wxPayNo"
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:switch" />
                    </el-icon>
                  </template>
                  对账
                </el-button>
                <el-button
                  type="primary"
                  text
                  size="small"
                  @click="
                    data.dialogFormVisible = true;
                    data.id = scope.row.id;
                  "
                >
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:switch" />
                    </el-icon>
                  </template>
                  付款
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog
          v-model="data.dialogFormVisible"
          title="手动付款确认"
          width="500px"
        >
          <el-form :model="data.form">
            <el-form-item label="付款备注" label-width="auto">
              <el-input
                type="textarea"
                v-model="data.form.remark"
                autocomplete="off"
                :autosize="{ minRows: 3, maxRows: 7 }"
              />
            </el-form-item>
            <!-- <el-form-item label="Zones" :label-width="formLabelWidth">
              <el-select
                v-model="form.region"
                placeholder="Please select a zone"
              >
                <el-option label="Zone No.1" value="shanghai" />
                <el-option label="Zone No.2" value="beijing" />
              </el-select>
            </el-form-item> -->
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.dialogFormVisible = false"
                >取消</el-button
              >
              <el-button
                type="primary"
                @click="
                  handleUpdate();
                  data.dialogFormVisible = false;
                "
              >
                确认付款
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>

      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
.ml-99 {
  background-color: rgb(255 0 0 / 30%);
  color: #f00;
  border: 1px solid #f00;
}
</style>
